package dao.impl;

import java.sql.*;

/*
工具类
连接数据库和释放资源
* */
public class BaseDao {
    private static String driverName = "oracle.jdbc.driver.OracleDriver";
    private static String url = "jdbc:oracle:thin:@localhost:1521:orcl";
    private static String username = "kz";
    private static String passwrd = "root";
    public static Connection connection = null;
    public static PreparedStatement statement = null;
    public static ResultSet resultSet = null;

    /*
     return 数据库连接对象
     throws Exception
    * */
    public static Connection getConnection() throws Exception {
        Class.forName(driverName);
         connection = DriverManager.getConnection(
                url, username, passwrd);
        return connection;
    }
//修改数据
    public static int update(String sql,Object[] objects)throws Exception{
         statement = connection.prepareStatement(sql);
         if (objects!=null&& objects.length>0) {
             for (int i = 0; i < objects.length; i++) {
                 statement.setObject(i + 1, objects[i]);
             }
         }
        int update = statement.executeUpdate();
        return update;
    }

    //查询操作
    public static  ResultSet query(String sql,Object[] objects)throws Exception{
        statement = connection.prepareStatement(sql);
        if (objects!=null&& objects.length>0) {
            for (int i = 0; i < objects.length; i++) {
                statement.setObject(i + 1, objects[i]);
            }
        }
         resultSet = statement.executeQuery();
        return resultSet;
    }
    /*
     * 查询操作释放资源
     * resultSet
     * connection
     * statement
     * */
    public static void close(ResultSet resultSet,Statement statement, Connection connection) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /*
     * 增删改时释放资源
     * statement
     * connection
     * */
    public static void close(Connection connection, Statement statement) {

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
